package co.za.itweb.brainstormlite;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ParserError")
public class Login extends Activity {
	LoginTask LT;
	EditText user;
	EditText pass;
	private Vector<LoginFeed> loginList = new Vector<LoginFeed>(0);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		Button close = (Button) findViewById(R.id.close);
		Button login = (Button) findViewById(R.id.btn_login);
		user = (EditText) findViewById(R.id.usn);
		pass = (EditText) findViewById(R.id.pwd);

		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(111, returnIntent);
				finish();
			}
		});

		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (user.getText().length() < 1 || pass.getText().length() < 1) {
					Toast.makeText(getApplicationContext(),
							"Please fill in all required fields !",
							Toast.LENGTH_SHORT).show();
				} else {

					LT = new LoginTask(getApplicationContext(), user.getText()
							.toString(), pass.getText().toString());
					LT.execute();

				}
			}
		});
	}

	public void addLoginData() {
		JSONArray JArray;
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					MenuActivity.LOGIN_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.brainstormlite.login",
					"login");

			if (prefName.length() > 5) {
				JArray = new JSONArray(prefName);
			} else {
				JArray = new JSONArray();
			}

			JSONObject jObjectType = new JSONObject();

			try {
				jObjectType.put("user", user.getText());
				jObjectType.put("pass", pass.getText());
				jObjectType.put("expiry", loginList.get(0)._itemlist.get(0)
						.get_expiry());

				JArray.put(jObjectType);
				StringBuilder buf = new StringBuilder();

				buf.append(JArray).append("\n");

				SharedPreferences settings = getSharedPreferences(
						MenuActivity.LOGIN_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.clear();

				editor.putString("co.za.brainstormlite.login", buf.toString());
				editor.commit();

			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (JSONException e) {
			e.printStackTrace();

		}

	}

	private class LoginTask extends AsyncTask<Void, Integer, Void> {
		LoginFeed loginFeed;
		ProgressDialog dialog;
		String u;
		String p;

		int id;

		public LoginTask(Context activity, String username, String password) {

			this.u = username;
			this.p = password;
			/*
			 * dialog = new ProgressDialog(activity);
			 * dialog.setMessage("Loading Favorite...");
			 * dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			 * dialog.setCancelable(true); dialog.setMax(100);
			 * dialog.setOnCancelListener(new
			 * DialogInterface.OnCancelListener(){ public void
			 * onCancel(DialogInterface dialog) { LT.cancel(true);
			 * Toast.makeText(getApplicationContext(), "Loading canceled...",
			 * Toast.LENGTH_SHORT).show(); } }); dialog.show();
			 */

		}

		@Override
		protected Void doInBackground(Void... params) {

			loginFeed = getFeed("http://itweb.mobi/brainstorm/feed/checklogin.php?usn="
					+ u + "&pwd=" + p);

			if (loginFeed != null) {
				loginList.add(loginFeed);

				publishProgress();
				if (isCancelled()) {
					loginList.clear();
					if (dialog.isShowing()) {
						dialog.dismiss();
					}

					return null;
				}

			} else {
				System.out.println("NULLLLLL");
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		@Override
		protected void onPostExecute(Void result) {
			/*
			 * if(dialog.isShowing()){ dialog.dismiss(); }
			 */
			if (loginList.get(0)._itemlist.get(0).get_name().length() < 2) {
				Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(111, returnIntent);
				finish();
			} else {
				if (compareDates(loginList.get(0)._itemlist.get(0)
						.get_expiry().toString().substring(0, 10))) {
					addLoginData();
					Intent returnIntent = new Intent();
					returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					setResult(222, returnIntent);
					finish();
				} else {
					
					Intent returnIntent = new Intent();
					returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					setResult(111, returnIntent);
					finish();
				}

			}

			// Intent intent = new Intent(getApplicationContext(),
			// SingleFavorite.class);
			// intent.putExtra("id", 0);
			// intent.putExtra("feedid", 0);
			// startActivity(intent);

		}

	}

	public boolean compareDates(String givenDateString) {
		Calendar cal = Calendar.getInstance();
		boolean result = false;
		Calendar currentcal = Calendar.getInstance();
		String[] separated = givenDateString.substring(0, 10).split("-");
		cal.set(Integer.parseInt(separated[0]), Integer.parseInt(separated[1]),
				Integer.parseInt(separated[2]));
		currentcal.set(currentcal.get(Calendar.YEAR),
				currentcal.get(Calendar.MONTH),
				currentcal.get(Calendar.DAY_OF_MONTH));
		if (cal.before(currentcal)) {
			System.out.print("Current date("
					+ new SimpleDateFormat("yyyy-MM-dd").format(currentcal
							.getTime()) + ") is greater than the given date "
					+ new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
			result = false;
		} else if (cal.after(currentcal)) {
			System.out.print("Current date("
					+ new SimpleDateFormat("yyyy-MM-dd").format(currentcal
							.getTime()) + ") is less than the given date "
					+ new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
			result = true;
		} else {
			System.out.print("Both date are equal.");
			result = true;
		}

		return result;
	}

	public LoginFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			LoginHandler theRssHandler = new LoginHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
					+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
					+ ee.toString());
			return null;
		}
	}
	
	 @Override
	  public boolean onKeyDown(int keyCode, KeyEvent event) {
	      if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	  Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(111, returnIntent);
				finish();
	        
	          return true;
	      }
	      return super.onKeyDown(keyCode, event);
	  }

}